package com.myblog.config.filter;

import com.myblog.common.CommonConstant;
import com.myblog.config.exception.ValidateCodeException;
import com.myblog.config.properties.SecurityProperties;
import com.myblog.config.security.handle.CustomAuhtenticationFailureHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ImageCodeValidateFailter extends OncePerRequestFilter {

    @Autowired
    SecurityProperties securityProperties;

    @Autowired
    CustomAuhtenticationFailureHandler customAuhtenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if(securityProperties.getLoginProcessingUrl().equals(httpServletRequest.getRequestURI())&&httpServletRequest.getMethod().equalsIgnoreCase("post")){
            try {
                validate(httpServletRequest);
            }catch (AuthenticationException e){
                customAuhtenticationFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
                return;
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    private void validate(HttpServletRequest httpServletRequest) throws ValidateCodeException {
        String sessionCode = (String)httpServletRequest.getSession().getAttribute(CommonConstant.SESSION_KEY);

        String inputCode = httpServletRequest.getParameter("code");

        if(!StringUtils.isNoneBlank()){
            throw new ValidateCodeException("验证码不能为空");
        }
        if(!sessionCode.equalsIgnoreCase(inputCode)){
            throw new ValidateCodeException("验证码输入错误");
        }
    }
}
